package com.videostreaming.controller;

import com.videostreaming.controller.base.BaseDbController;
import com.gooddies.wiring.annotations.WiringComponent;
import com.videostreaming.data.User;
import com.videostreaming.data.Video;
import com.wiringweb.annotations.Controller;
import com.wiringweb.annotations.UrlBinding;
import com.wiringweb.resolution.ErrorResolution;
import com.wiringweb.resolution.Resolution;
import com.wiringweb.resolution.VelocityResolution;
import org.apache.commons.lang3.RandomStringUtils;

@Controller
@WiringComponent(singleton = true)
public class StreamController extends BaseDbController {

    @UrlBinding("/stream\\.html")
    public Resolution stream() {
        if (getSessionParameter(LOGGED_USER) == null) {
            return new ErrorResolution(403, "Not authentificated");
        }

        User user = (User) getSessionParameter(LOGGED_USER);
        Video pv = getDb().getVideoForUser(user.getId());
        if (pv == null) {
            String videoHash = RandomStringUtils.randomAlphanumeric(10);
            pv = new Video();
            pv.setUserId(user.getId());
            pv.setVideoHash(videoHash);
            pv.setPlay(false);
            getDb().insertVideo(pv);
        }

        addRequestParameter("streamId", pv.getVideoHash());
        return new VelocityResolution("stream.vm");
    }
}
